package org.zpmis.api.http;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import org.zpmis.common.result.PlatformResult;
import org.zpmis.common.result.ResultCode;
import org.zpmis.config.MinioConfig;
import org.zpmis.util.MinioUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/file")
public class FileController   {

    final static Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private   MinioUtil minioUtil;

    @Autowired
    private MinioConfig minioConfig;


    /**
     * 上传文件
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public PlatformResult upload(@RequestParam("file") MultipartFile file) {
        if (file == null) {
            return PlatformResult.builder().code(ResultCode.PARAM_ERROR.code()).msg("file is null").build();
        }
        try {
            String contentType = file.getContentType();
            String originalFilename = file.getOriginalFilename();
            //随机文件UUID名
            String fileName = minioUtil.generateRandomFileName(originalFilename);

            String uploadName = minioUtil.uploadStream(MinioUtil.DEFAUT_BUCKET, fileName, file.getInputStream(), contentType);
            //封装返回信息
            Map<String,String> resultMap = new HashMap<>();
            resultMap.put("originalFilename",originalFilename);
            resultMap.put("uploadName",uploadName);
            return PlatformResult.success(resultMap);
        } catch (Exception e) {
            logger.error("上传服务异常",e);
            return PlatformResult.failure();
        }
    }

    /**
     * 下载文件
     * @param fileName 文件名
     * @param response
     * @return
     */
    @RequestMapping("/download/{filename}")
    public void download( @PathVariable("filename") String fileName, HttpServletResponse response) throws IOException {

        if (StringUtils.isEmpty(fileName)) {
            return;
        }
        InputStream inputStream = null;
        try {
            inputStream = minioUtil.get(fileName,MinioUtil.DEFAUT_BUCKET);
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setCharacterEncoding("UTF-8");
            response.setContentType(minioUtil.getObjectState(MinioUtil.DEFAUT_BUCKET,fileName).contentType());
            IOUtils.copy(inputStream,response.getOutputStream());

            return ; //成功不需返回任何信息
        } catch (Exception e) {
            logger.error("下载服务异常",e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,e.getMessage());
            return;
        }finally {
            if(inputStream != null){
                inputStream.close();
            }
        }
    }

    /**
     * 返回图片地址
     * @param fileNmae 文件名称
     * @return
     */
    @GetMapping("/img/url/{filename}")
    public String getImgUrl(@PathVariable("filename") String fileNmae,@RequestParam int shareExpiryTime) throws Exception {
        return minioUtil.shareUrl(MinioUtil.DEFAUT_BUCKET,fileNmae,shareExpiryTime);
    }
    /**
     * 在浏览器预览图片
     * @param fileName 文件名
     * @param response
     * @throws Exception
     */
    @GetMapping("/preViewPicture/{filename}")
    public void preViewPicture(@PathVariable("filename") String fileName, HttpServletResponse response) throws Exception{
     //   String subStr = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
//        if(subStr.equals("pdf")){
//            response.setContentType("application/pdf");
//        }else if(subStr.equals("png") || subStr.equals("jpg")){
//            response.setContentType("image/jpeg");
//        }else{
//            response.setContentType("text/html");
//        }
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            InputStream  inputStream = minioUtil.get(fileName,MinioUtil.DEFAUT_BUCKET);
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int n = 0;
            while (-1 != (n = inputStream.read(buffer))) {
                output.write(buffer, 0, n);
            }
            byte[] bytes = output.toByteArray();
            out.write(bytes == null ? new byte[0]:bytes);
            out.flush();
        }finally {
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * 移除图片
     * @param fileName 文件名
     * @return
     */
    @GetMapping("/remove/{filename}")
    public PlatformResult remove(@PathVariable("filename") String fileName){
        try {
            minioUtil.remove(fileName,MinioUtil.DEFAUT_BUCKET);
            return PlatformResult.builder().code(ResultCode.SUCCESS.code()).msg("success").build();
        } catch (Exception e) {
            logger.error("删除文件服务异常",e);
            return PlatformResult.builder().code(ResultCode.ERROR.code()).msg(e.getMessage()).build();
        }
    }
}
